package com.myy.purchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myy.common.utils.MD5Util;
import com.myy.purchase.entity.Purchase;
import com.myy.purchase.mapper.PurchaseMapper;
import com.myy.purchase.service.IPurchaseService;
import com.myy.common.entity.FebsConstant;
import com.myy.common.entity.QueryRequest;
import com.myy.common.utils.SortUtil;
import com.myy.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements IPurchaseService {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public IPage<Purchase> findPurchase(Purchase purchase, QueryRequest request) {
        QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(purchase.getName())) {
            queryWrapper.lambda().like(Purchase::getName, purchase.getName());
        }

        Page<Purchase> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "createTime", FebsConstant.ORDER_DESC, true);

        return this.page(page, queryWrapper);
    }

    @Override
    public void createPurchase(Purchase purchase) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        purchase.setCreateUser(user.getUserId());
        purchase.setCreateTime(new Date());
        save(purchase);
    }
}
